<template>
	<view class="">
		<!-- 导航栏 -->
		<view class="navbar" :style="{ paddingTop: top + 'rpx' }">
			<view class="left" @click="navigateBack">
				<uni-icons type="left" size="28"></uni-icons>
			</view>
			<view class="title">选择收货地址</view>
			<view class="right"></view>
		</view>

		<!-- 主内容区 -->
		<view class="cantain" :style="{ top: top + 60 + 'rpx' }">
			<!-- 已选择地址 -->
			<view class="statu">
				<text>已选择的地址：</text>
				<text>{{ selectedAddressText || '暂无选择' }}</text>
			</view>
	       <view class="location">
				<view class="location-title">
					<uni-icons type="location" size="28" color="#ff4d4f"></uni-icons>
					<text>当前定位</text>
					<view class="location-btn" @click="reloadLocation">回本地</view>
					<view class="location-btn" @click="otherLocation">重新定位</view>
				</view>
				<view class="address">{{ storeData.address || '定位中...' }}</view>
			</view>
			<!-- 搜索框 -->
			<view class="search">
				
		
				<input @confirm="search" type="search" v-model="keyword" placeholder="搜索小区/写字楼等" />
				<uni-icons type="search" size="26" color="#999" @click="search"></uni-icons>
			</view>

			<!-- 当前定位 -->
		

			<!-- 我的地址 -->
			<view class="myaddress">
				<view class="title">
					<uni-icons type="home" size="20" color="#55aaff"></uni-icons>
					<text>我的地址（{{ addressList.length }}）</text>
					</view>
				<scroll-view class="" scroll-y="true">
					<view class="addressList" v-for="(item, index) in addressList" :key="item._id || index" @click="selectMyAddress(item)" @longpress="selcDelItem(index)">
						<view class="poi-name">
							<view class="poi-name-txt">
								<text>{{ item.poiName }}</text>
							</view>
							<view class="address-tag" v-if="item.tag">{{ item.tag }}</view>
						</view>
						<view class="address-detail">
							{{ item.detailAddress }}
						</view>
						<view class="address-tel">{{item.recipient_name}}-{{ item.recipient_phone }}</view>
						<view class="delIcon" @click="deleteItem(index)">
							<uni-icons type="trash" color="#ff5500" size="30"></uni-icons>
						</view>
						
					</view>
					<view class="empty-address" v-if="addressList.length === 0">
						<text>暂无已保存的地址</text>
					</view>
				</scroll-view>
			</view>

			<!-- 附近地址 -->
			<view class="nearbyMe">
				<view class="title">
					<uni-icons type="location" size="20" color="#55aaff"></uni-icons>
					<text>附近地址</text>
					</view>
				<scroll-view class="scrollnearbyme" scroll-y="true">
					<view
						class="nearbyitem"
						v-for="(item, index) in nearbylist"
						:key="index"
						@click="selcaddress(index)"
						:style="{ backgroundColor: selectedIndex === index ? selectedColor : defaultColor }"
					>
						<view class="nearbyitem-name">{{ item.title }}</view>
						<view class="nearbyitem-address">{{ item.address }}</view>
						<view class="nearbyitem-distance">距离 {{ (item.distance / 1000).toFixed(2) }}km</view>
					</view>
					<view class="empty-nearby" v-if="nearbylist.length === 0">
						<text>未获取到附近地址</text>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 完善地址弹窗 -->
		<uni-popup ref="popup" class="uni-popup-top" :mask="true">
			<view class="selced">
				<view class="selc-title">完善地址信息</view>
				<view class="selc-name">{{ selcAddress.title || '未选择地址' }}</view>
				<view class="selc-address">{{ selcAddress.address || '' }}</view>

				<!-- 详细地址（门牌号） -->
				<input type="text" v-model="sumbitForm.detailAddress" placeholder="输入详细地址，如门牌号/单元号" />

				<!-- 收货人 -->
				<input type="text" v-model="sumbitForm.recipient_name" placeholder="请输入收货人姓名" />

				<!-- 手机号 -->
				<input type="tel" v-model="sumbitForm.telephone" placeholder="请输入手机号" maxlength="11" />

				<!-- 地址标签 -->
				<view class="tag-title">地址标签</view>
				<view class="tag">
					<view class="tagitem" :class="{ selcedtag: tag === '公司' }" @click="handleTag('公司')">公司</view>
					<view class="tagitem" :class="{ selcedtag: tag === '家' }" @click="handleTag('家')">家</view>
					<view class="tagitem" :class="{ selcedtag: tag === '单位' }" @click="handleTag('单位')">单位</view>
					<view class="tagitem" :class="{ selcedtag: tag === '其它' }" @click="handleTag('其它')">其它</view>
				</view>

				<!-- 操作按钮：修复单引号为双引号 -->
				<view class="btn-group">
					<button type="default" @click="cancel">取消</button>
					<button type="primary" @click="sure">确认保存</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>


const amap = uniCloud.importObject('uni-map-co',{customUI:true});
const db = uniCloud.databaseForJQL();
export default {
	data() {
		return {
			action:'',
			addressList: [], // 我的地址列表
			nearbylist: [], // 附近地址列表
			top: 0, // 导航栏顶部安全距离
			tag: '其它', // 当前选中标签（默认其它）
			selectedColor: '#C7fff7', // 选中背景色
			defaultColor: '#fff', // 默认背景色
			selcAddress: {}, // 选中的附近地址
			selectedIndex: -1, // 附近地址选中索引（-1=未选中）
			selectedAddressText: '', // 已选择地址文本展示
			locationText: '', // 当前定位文本
			keyword: '',
			city:'',
			selcIndex:-1,
			sumbitForm: {
				poiName: '', // 收货人
				recipient_name: '',
				recipient_phone: '',
				tag: '',
				userId: '',
				poiAddress: '',
				detailAddress: '',
				location: '',
				createTime: '',
				isDefault: '',
				orderSureEvent:null
			}
		};
	},
	computed: {
		// 从store获取系统信息
		systemInfo() {
			return this.$store.state.msg.systemInfo || uni.getSystemInfoSync();
		},
		// 从store获取用户信息
		userInfo() {
			return this.$store.state.msg.user || {};
		},
		storeData(){
			return this.$store.state.msg
		}
		
	},
	async onLoad(options) {
		// 初始化顶部安全距离
		this.top = this.systemInfo.safeArea.top * (750 / this.systemInfo.windowWidth);
		// 初始化用户ID
		this.sumbitForm.userId = this.userInfo.userId || '';
		// 加载我的地址和附近地址
		await Promise.all([this.getUsedAddress(), this.searchPoi('')]);
		this.$store.commit('cart/SET_orderAddress',this.addressList)
		uni.setStorageSync('addressList',this.addressList)
		
		// 若从结算页跳转，回显已选择地址
		if (options.selectedAddressId) {
			this.selectedAddressText = this.addressList.find((item) => item._id === options.selectedAddressId)?.detailAddress || '';
		}
		if(options.action){
			console.log("....",options);
				this.action=options.action
		}
		this.orderSureEvent=this.getOpenerEventChannel()
	
		
	},
	methods: {
		// 返回上一页
		navigateBack() {
			uni.navigateBack({ delta: 1 });
		},
		// 跳转到新增地址页（独立新增页面，可选）

		search(e) {
			if(!this.keyword){
				uni.showToast({
					title:'请输入小区/楼宇名称',
					position:'center'
				})
				return
			}
			const keyword = this.keyword;
			console.log(e);
			this.searchPoi(keyword);
		},
		onchange(e){
			console.log(e);
		},
		onnodeclick(e){
			console.log(e)
		},
		selcDelItem(index){
		   this.selcIndex=index	
		},
	async deleteItem(index) {
	  const id = this.addressList[index]._id;
	  // 二次确认（避免误操作）
	  uni.showModal({
	    title: '提示',
	    content: '确定要删除该地址吗？',
	     success:async (res)=> {
	      if (res.confirm) {
	        try {
	          uni.showLoading({ title: '删除中...' });
	          // 1. 修正集合名称 + 等待删除完成
	          const delRes = await db.collection('orderAddress').where({ _id: id }).remove();
	          
	          // 2. 判断删除是否成功（不同数据库返回格式可能不同，需根据实际调整）
	          // 例如：uniCloud返回 { affectedDocs: 1 }，微信云返回 { stats: { removed: 1 } }
	          const isSuccess = delRes.affectedDocs > 0 || (delRes.stats && delRes.stats.removed > 0);
	          
	          if (isSuccess) {
	            // 3. 正确查找索引并删除当前项
	            const idx = this.addressList.findIndex(item => item._id === id);
	            if (idx !== -1) {
	              this.addressList.splice(idx, 1); // 仅删除当前项
	              
	              // 4. 更新本地存储和Vuex
	              uni.setStorageSync('addressList', this.addressList);
	              this.$store.commit('msg/SET_addressList', this.addressList);
	              
	              uni.showToast({ title: '删除成功' });
	            }
	          } else {
	            uni.showToast({ title: '删除失败', icon: 'none' });
	          }
	        } catch (e) {
	          console.error('删除地址错误:', e);
	          uni.showToast({ title: '删除失败，请重试', icon: 'none' });
	        } finally {
	          uni.hideLoading(); // 无论成功失败，都关闭loading
	        }
	      }
	    }
	  });
	},
		
		// 重新定位
		async reloadLocation() {
			const location={lng:this.$store.state.msg.senderLocation?.longitude,lat:this.$store.state.msg.senderLocation?.latitude }
			this.$store.commit('msg/SET_location',this.storeData.senderLocation)
			this.searchPoi('',location)
		},
		async otherLocation(){
			uni.navigateTo({
				url:'/pages/main/main'
			})
		},
		// 加载我的地址
		async getUsedAddress() {
			try {
				const res = await db.collection('orderAddress').where({ userId: this.userInfo.userId }).orderBy('createTime', 'desc').get();
			
				this.addressList = res.data || [];
				// 初始化已选择地址（默认第一个）
				if (this.addressList.length > 0 && !this.selectedAddressText) {
					this.selectedAddressText = this.addressList[0].poiName;
				}
			} catch (e) {
				console.error('加载我的地址失败:', e);
				this.addressList = [];
				uni.showToast({ title: '地址加载失败', icon: 'none' });
			}
		},
		// 加载附近地址
		async searchPoi(keyword, customLocation = null) {
			console.log(keyword, customLocation);
			// 优先使用自定义定位，否则从store获取
			const location = customLocation || {
				lng: this.$store.state.msg.location?.longitude || 116.404,
				lat: this.$store.state.msg.location?.latitude || 39.915
			};
			// 更新定位文本
			this.locationText = this.$store.state.msg.address || '已获取定位';

			try {
				const searchData = {
					keyword: keyword,
					location: location,
					radius: 5000, // 搜索半径5km
					auto_extend: 1,
					get_subpois: true,
					orderby: 'distance', // 按距离排序
					page_index: 1,
					page_size: 20,
					types: '120000', // 地址类POI
					city: ''
				};
				const res = await amap.search(searchData);
				console.log('附近地址', res);
				this.nearbylist = (res.result?.result?.data || []).filter((item) => item.address && item.title).sort((a, b) => a.distance - b.distance);
				
			} catch (e) {
				console.warn('获取附近地址失败:', e.message);
				this.nearbylist = [];
				this.locationText = '获取附近地址失败';
			}
		},
		// 选择我的地址
		selectMyAddress(item) {
			this.selectedAddressText = item.poiName;
			// 若从结算页跳转，返回选中地址
			uni.$emit('selectAddress', item);
			console.log('8888',item);
			this.$store.commit('cart/SET_lastAddress',item)
			uni.setStorageSync('lastAddress',item)
	         this.orderSureEvent.emit('fromB',item)
			this.navigateBack();
		},
		// 选择附近地址
		selcaddress(index) {
		this.selectedIndex = this.selectedIndex === index ? -1 : index;
		// 赋值选中地址
		this.selcAddress = this.nearbylist[index];
		console.log(this.action&&this.action==='selec');
			if(this.action&&this.action==='selec'){
				uni.$emit('selectAddress',this.selcAddress)
				uni.navigateBack()
				return
			}
	    	// 同步基础地址到表单
			this.sumbitForm.poiName = this.selcAddress?.title || '';
			this.sumbitForm.poiAddress=this.selcAddress?.address||""
			// 打开完善信息弹窗
		
			this.$refs.popup.open();
		},
		// 选择地址标签
		handleTag(tag) {
			this.tag = tag;
			this.sumbitForm.tag = tag;
		},
		// 取消完善地址
		cancel() {
			this.$refs.popup.close();
			// 重置表单（避免下次打开有残留）
			this.sumbitForm.detailAddress = '';
			this.sumbitForm.recipient_name = '';
			this.sumbitForm.telephone = '';
		},
		// 确认保存地址
		async sure() {
			// 表单验证
			const { recipient_name, poiName, telephone, detailAddress, poiAddress } = this.sumbitForm;

			if (!/^1[3-9]\d{9}$/.test(telephone.trim())) {
				return uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
			}
			if (!detailAddress.trim()) {
				return uni.showToast({ title: '请输入详细地址（门牌号）', icon: 'none' });
			}
			if (!poiAddress.trim()) {
				return uni.showToast({ title: '请先选择基础地址', icon: 'none' });
			}
			if (!recipient_name.trim()) {
				return uni.showToast({ title: '请输入收件人', icon: 'none' });
			}

			// 构造完整地址数据
			const newAddress = {
				poiName: poiName.trim(), // 收货人
				recipient_name: recipient_name.trim(), // 冗余字段（保持兼容）
				recipient_phone: telephone.trim(), // 手机号
				tag: this.sumbitForm.tag, // 地址标签
				userId: this.sumbitForm.userId, // 用户ID
				poiAddress:poiAddress.trim(),
				detailAddress: detailAddress.trim(), // 详址
				location: this.selcAddress?.location ? new db.Geo.Point(this.selcAddress.location.lng, this.selcAddress.location.lat) : null,
				createTime: Date.now(), // 创建时间
				isDefault: this.addressList.length === 0 // 若没有地址，默认设为默认地址
			};

			try {
				uni.showLoading({ title: '保存中...' });
				// 新增地址到数据库
				const res = await db.collection('orderAddress').add(newAddress);
				if (res.id || res._id) {
					this.$store.commit('cart/SET_lastAddress',{id:res.id,...newAddress})
					uni.setStorageSync('lastAddress',{id:res.id,...newAddress})
				 const addressList = uni.getStorageSync('addressList') || []; // 兼容初始为空的情况
				 // 新地址添加到数组头部
				 uni.setStorageSync('addressList', [{ id: res.id, ...newAddress }, ...addressList]);
			
				
					
					uni.hideLoading();
					uni.showToast({ title: '地址保存成功' });
					// 关闭弹窗
					this.$refs.popup.close();
					// 刷新我的地址列表
					await this.getUsedAddress();
					// 重置表单和选中状态
					this.sumbitForm = {
						poiName: '',
						tag: '其它',
						recipient_name: '',
						userId: this.sumbitForm.userId,
						poiAddress: '',
						detailAddress: '',
						location: null,
						recipient_phone: '', // 手机号
					};
					this.selectedIndex = -1;
				}
			} catch (e) {
				uni.hideLoading();
				console.error('保存地址失败:', e);
				uni.showToast({ title: '保存失败，请重试', icon: 'none' });
			}
		}
	}
};
</script>

<style lang="scss" scoped>
// 全局变量
$color-primary: #ff4d4f; // 主题色
$color-gray: #999; // 次要文本色
$color-lightgray: #f5f5f5; // 背景色
$color-border: #eee; // 边框色
$spacing: 24rpx; // 基础间距
$radius: 12rpx; // 圆角
$font-sm: 24rpx; // 小字体
$font-md: 26rpx; // 中字体
$font-lg: 28rpx; // 大字体

// 导航栏样式
.navbar {
	display: flex;
	position: fixed;
	left: 0;
	top: 0;
	right: 0;
	align-items: center;
	height: 80rpx;
	padding: 0 $spacing;
	background-color: #fff;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	z-index: 99;

	.left,
	.right {
		width: 180rpx;
		height: 100%;
		display: flex;
		align-items: center;
		font-size: $font-md;
		color: #333;
	}

	.left {
		justify-content: flex-start;
		cursor: pointer;
		uni-icons {
			font-size: 36rpx;
			color: #333;
		}
	}

	.right {
		justify-content: flex-end;
		color: $color-primary;
		cursor: pointer;
	}

	.title {
		flex: 1;
		text-align: center;
		font-size: $font-lg;
		font-weight: 600;
		color: #333;
	}
}

// 主容器样式
.cantain {
	background-color: $color-lightgray;
	min-height: 100vh;
	padding: $spacing;
	box-sizing: border-box;
	position: fixed;
	left: 0;
	right: 0;
	overflow-y: auto; // 主容器可滚动（避免内容溢出）
}

// 已选择地址区域
.statu {
	background-color: #c7fff7;
	padding: $spacing;
	border-radius: $radius;
	margin-bottom: $spacing;
	text {
		font-size: $font-md;
		color: #55aa7f;
		&:nth-child(2) {
			margin-left: 8rpx;
			font-weight: 500;
		}
	}
}

// 搜索框样式
.search {
	background-color: #f0f0f0;
	height: 70rpx;
	border-radius: 35rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: $spacing;
	padding: 0 $spacing;
	cursor: pointer;
	transition: background-color 0.2s;
	input {
		background-color: #fff;
		height: 60rpx;
		width: 500rpx;
		padding: 10rpx 20rpx; /* 左右内边距稍大，提升输入体验 */
		border-radius: 30rpx;
		border: 1px solid #eee; /* 增加边框，区分输入框区域 */
		box-sizing: border-box; /* 确保padding不影响整体尺寸 */
		font-size: 28rpx; /* 输入文字大小，与占位符区分 */
		&::placeholder {
			font-size: 24rpx;
		}
	}

	&:active {
		background-color: #e8e8e8;
	}

	text {
		font-size: $font-md;
		color: $color-gray;
		margin-left: 12rpx;
	}
}

// 当前定位区域
.location {
	width: 100%;
	background-color: #fff;
	border-radius: $radius;
	padding: $spacing;
	margin-bottom: $spacing;

	.location-title {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;

		text {
			font-size: $font-lg;
			color: #333;
			font-weight: 500;
		}

		.location-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-left: auto;
			margin-right: 20rpx;
			padding: 5rpx 10rpx;
			border-radius: 20rpx;
			width: 200rpx;
			height: 40rpx;
			color: #09bb07;
			background-color: #bdffe2;
			font-size: $font-sm;
			cursor: pointer;
		}
	}

	.address {
		font-size: $font-md;
		color: #666;
		line-height: 1.5;
		padding-left: 40rpx; // 与图标对齐
	}
}

// 我的地址区域
.myaddress {
	background-color: #fff;
	border-radius: $radius;
	margin-bottom: $spacing;
	overflow: hidden;

	.title {
		height: 70rpx;
		line-height: 70rpx;
		padding: 0 $spacing;
		font-size: $font-lg;
		color: #333;
		font-weight: 500;
		border-bottom: 1px solid $color-border;
	}

	scroll-view {
		max-height: 400rpx; // 限制高度，超出可滚动
	}

	.addressList {
		padding: 10rpx 50rpx;
		border-bottom: 1px solid $color-border;
		font-size: $font-md;
		color: #666;
		line-height: 1.5;
		cursor: pointer;
		position: relative;
		transition: background-color 0.2s;

		&:last-child {
			border-bottom: none;
		}

		&:active {
			background-color: $color-lightgray;
		}
		.address-box {
			display: flex;
		}
		.poi-name{
			display: flex;
			gap:10rpx
		}
		.poi-name-txt{
			font-size: 32rpx;
			font-weight: 600;
		}
		.address-tag {
			display: inline-block;
			padding: 4rpx 12rpx;
			background-color: #f0f0f0;
			color: #666;
			font-size: $font-sm;
			border-radius: 16rpx;
			margin-bottom: 8rpx;
		}

		.address-name {
			font-weight: 600;
			font-size: 32rpx;
			color: #333;
			margin-bottom: 8rpx;
		}

		.address-detail {
			margin-bottom: 8rpx;
			word-break: break-all;
		}

		.address-tel {
			color: #afafaf;
		}
	}
.delIcon{
	position: absolute;
	top: 0;
	right:50rpx;
}
	.empty-address {
		height: 200rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: $color-gray;
		font-size: $font-md;
	}
}

// 附近地址区域
.nearbyMe {
	background-color: #fff;
	border-radius: $radius;
	overflow: hidden;
	

	.title {
		height: 70rpx;
		line-height: 70rpx;
		padding: 0 $spacing;
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		border-bottom: 1px solid $color-border;
	}

	.scrollnearbyme {
		max-height: 600rpx; // 限制高度，超出可滚动
	}

	.nearbyitem {
		padding: $spacing;
		border-bottom: 1px solid $color-border;
		cursor: pointer;
		transition: background-color 0.2s;
		padding-left: 50rpx;

		&:last-child {
			border-bottom: none;
		}

		&:active {
			background-color: $color-lightgray;
		}

		.nearbyitem-name {
			font-weight: 500;
			padding: 5rpx 10rpx;
			font-size: $font-lg;
			color: #333;
		}

		.nearbyitem-address {
			font-size: $font-md;
			color: #666;
			padding: 5rpx 10rpx;
			line-height: 1.4;
			margin-bottom: 8rpx;
		}

		.nearbyitem-distance {
			font-size: $font-sm;
			color: $color-gray;
			padding: 0 10rpx;
		}
	}

	.empty-nearby {
		height: 200rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: $color-gray;
		font-size: $font-md;
	}
}

// 完善地址弹窗样式
.selced {
	padding: 30rpx $spacing;
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0; // 顶部圆角
	padding-top: 20rpx;

	.selc-title {
		font-size: $font-lg;
		font-weight: 600;
		color: #333;
		margin-bottom: 40rpx;
		text-align: center;
	}

	.selc-name {
		font-size: $font-lg;
		color: #333;
		margin-bottom: 8rpx;
		padding: 0 10rpx;
	}

	.selc-address {
		font-size: $font-md;
		color: #666;
		margin-bottom: 24rpx;
		padding: 0 10rpx 24rpx;
		border-bottom: 1px solid $color-border;
		word-break: break-all;
	}

	// 输入框样式
	input {
		width: 100%;
		height: 80rpx;
		padding: 0 20rpx;
		margin-bottom: 20rpx;
		border: 1px solid $color-border;
		border-radius: $radius;
		font-size: $font-md;
		box-sizing: border-box;
		transition: border-color 0.2s;

		&:focus {
			border-color: $color-primary;
			outline: none;
		}

		&::placeholder {
			color: $color-gray;
			font-size: $font-md;
		}
	}

	// 标签标题
	.tag-title {
		font-size: $font-md;
		padding: 10rpx 20rpx;
		color: #333;
		margin: 20rpx 0;
	}

	// 标签容器
	.tag {
		display: flex;
		justify-content: center;
		flex-wrap: wrap; // 支持换行
		gap: 16rpx;
		margin: 10rpx 0 30rpx;
	}

	// 标签样式
	.tagitem {
		padding: 10rpx 24rpx;
		border: 1px solid $color-border;
		border-radius: 30rpx;
		font-size: $font-md;
		color: #666;
		transition: all 0.2s;
		cursor: pointer;

		&:active {
			background-color: $color-lightgray;
		}
	}

	// 选中标签样式
	.selcedtag {
		color: $color-primary;
		border-color: $color-primary;
		background-color: rgba(255, 77, 79, 0.1);
		font-weight: 500;
	}

	// 按钮容器
	.btn-group {
		display: flex;
		gap: 20rpx;
		margin-top: 10rpx;
	}

	// 按钮样式：修复单引号为双引号
	// button[type="default"] {
	// 	border: 1px solid $color-border;
	// 	background-color: #fff;
	// 	color: #333;
	// }

	// button[type="primary"] {
	// 	background-color: $color-primary;
	// 	color: #fff;
	// }
}
</style>
